#include "admindevicemanage.h"
#include "ui_admindevicemanage.h"

AdminDeviceManage::AdminDeviceManage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AdminDeviceManage)
{
    ui->setupUi(this);
    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);  // 水平拉伸

    m_pLog = LogClass::getInstance();
    m_pSqliteManage = new SqliteManage;
    m_pSettingManage = new SettingManage(this);
    model = new DeviceModel(this,m_pSqliteManage->getDB());

    setupUI();
    loadData();

    ui->comboBoxFilter1->installEventFilter(this);

    connect(ui->comboBoxFilter1,QOverload<int>::of(&QComboBox::activated),this,[=](){
        QString currentData = ui->comboBoxFilter1->currentData().toString();
        QVector<QString> batchValues = m_pSettingManage->readBatchKeys("Group", currentData);
        QStringList comboItems = QStringList::fromVector(batchValues);
        ui->comboBoxFilter2->clear();
        ui->comboBoxFilter2->addItems(comboItems);
    });

    connect(ui->comboBoxFilter2, QOverload<int>::of(&QComboBox::activated), this, &AdminDeviceManage::applyFilter);

    connect(ui->btnResetFilter,&QPushButton::clicked,this,[=](){
        ui->comboBoxFilter1->clear();
        ui->comboBoxFilter2->clear();
    });
    connect(ui->btnAddGroup,&QPushButton::clicked,this,[=](){
        m_pAddDeviceGroup  = new AddDeviceGroup();
        if(addDialog()){
            m_pSettingManage->addSingleConfigData("Group",Group1+"_",Group2);//
        }
        if(ui->comboBoxFilter1->currentData()==Group1){
            QVector<QString> batchValues = m_pSettingManage->readBatchKeys("Group", Group1);
            QStringList comboItems = QStringList::fromVector(batchValues);
            ui->comboBoxFilter2->clear();
            ui->comboBoxFilter2->addItems(comboItems);
        }
        m_pLog->log(m_pSqliteManage,OPERATION_LOG,INFO,QString("添加了设备分组"),
                    m_pSqliteManage->getUserIdByName(username));
        delete m_pAddDeviceGroup;
    });
    connect(ui->btnModiGroup,&QPushButton::clicked,this,[=](){
        m_pModiGroup = new ModiGroupDialog(this);
        if(modiDialog()){
            int count = m_pSettingManage->updateConfigValuesByPrefix("Group",Group1+"_",Group2,NewGroup2);
            qDebug()<< "修改了：" << count <<"条数据";
        }
        if(ui->comboBoxFilter1->currentData()==Group1){
            QVector<QString> batchValues = m_pSettingManage->readBatchKeys("Group", Group1);
            QStringList comboItems = QStringList::fromVector(batchValues);
            ui->comboBoxFilter2->clear();
            ui->comboBoxFilter2->addItems(comboItems);
        }
        m_pLog->log(m_pSqliteManage,OPERATION_LOG,INFO,QString("修改了设备分组"),
                    m_pSqliteManage->getUserIdByName(username));
        delete m_pModiGroup;
    });
    connect(ui->btnDeleteGroup,&QPushButton::clicked,this,[=](){
        m_pDeleteGroup = new GroupDeleteDialog(this);
        if(deleteDialog()){
            int count = m_pSettingManage->deleteConfigValuesByPrefix("Group",Group1+"_",Group2);
            qDebug()<< "删除了：" << count <<"条数据";
        }
        if(ui->comboBoxFilter1->currentData()==Group1){
            QVector<QString> batchValues = m_pSettingManage->readBatchKeys("Group", Group1);
            QStringList comboItems = QStringList::fromVector(batchValues);
            ui->comboBoxFilter2->clear();
            ui->comboBoxFilter2->addItems(comboItems);
        }
        m_pLog->log(m_pSqliteManage,OPERATION_LOG,INFO,QString("删除了设备分组"),
                    m_pSqliteManage->getUserIdByName(username));
        delete m_pDeleteGroup;
    });
    connect(ui->btnResetFilter,&QPushButton::clicked,this,&AdminDeviceManage::clearFilter);
}

AdminDeviceManage::~AdminDeviceManage()
{
    delete ui;
    m_pSqliteManage->closeDatabase();
}

void AdminDeviceManage::loadComboxData()
{
    QComboBox* combo = ui->comboBoxFilter1;
    // 如果已经加载过数据则跳过
    if(combo->count() > 1 || combo->itemData(0).isValid())
        return;
    // 清空并重新加载
    combo->blockSignals(true); // 临时阻塞信号
    combo->clear();
    QStringList items = m_pSettingManage->getDistinctPrefixes("Group");
    if(items.isEmpty()){
        m_pLog->log(m_pSqliteManage,SYSTEM_LOG,INFO,QString("设备数据加载失败"));
    }
    //combo->addItems(items);
    foreach(const QString &item,items){
        if(item == "type"){
            ui->comboBoxFilter1->addItem("类型","type");
        }
        else if(item == "location"){
            ui->comboBoxFilter1->addItem("位置","location");
        }else{
            ui->comboBoxFilter1->addItem("其他","other");
        }
    }
    combo->blockSignals(false); // 恢复信号
    qDebug() << "已加载" << items.size() << "个选项";
}

bool AdminDeviceManage::addDialog()
{
    if (m_pAddDeviceGroup->exec() == QDialog::Accepted) {
        // 用户点击了"确定"按钮
        Group1 = m_pAddDeviceGroup->getComboxData();
        Group2 = m_pAddDeviceGroup->getLineEditData();
        return true;
        // 处理获取到的内容...
    } else {
        // 用户点击了"取消"或关闭按钮
        qDebug() << "对话框被取消";
        return false;
    }
}

bool AdminDeviceManage::modiDialog()
{
    if (m_pModiGroup->exec() == QDialog::Accepted) {
        // 用户点击了"确定"按钮
        Group1 = m_pModiGroup->getCombox1Data();
        Group2 = m_pModiGroup->getCombox2Data();
        NewGroup2 = m_pModiGroup->getLineEditData();
        return true;
        // 处理获取到的内容...
    } else {
        // 用户点击了"取消"或关闭按钮
        qDebug() << "对话框被取消";
        return false;
    }
}

bool AdminDeviceManage::deleteDialog()
{
    if (m_pDeleteGroup->exec() == QDialog::Accepted) {
        // 用户点击了"确定"按钮
        Group1 = m_pDeleteGroup->getCombox1Data();
        Group2 = m_pDeleteGroup->getCombox2Data();
        return true;
        // 处理获取到的内容...
    } else {
        // 用户点击了"取消"或关闭按钮
        qDebug() << "对话框被取消";
        return false;
    }
}

void AdminDeviceManage::setUserName(QString &name)
{
    this->username = name;
}

void AdminDeviceManage::applyFilter()
{
    if (ui->comboBoxFilter2->currentText().isEmpty()) {
        model->setFilter("");
    } else {
        //int colIndex = columnCombo->currentData().toInt();
        //QString colName = model->record().fieldName(colIndex);
        QString colName = ui->comboBoxFilter1->currentData().toString();
        QString filterValue = ui->comboBoxFilter2->currentText();
        // 简单筛选：字段 LIKE '%值%'
        model->setFilter(QString("%1 LIKE '%%2%'").arg(colName).arg(filterValue));
    }
    model->select();
}

void AdminDeviceManage::clearFilter()
{
    ui->comboBoxFilter2->clear();
    model->setFilter("");
    model->select();
}

bool AdminDeviceManage::eventFilter(QObject *watched, QEvent *event)
{
    // 只处理 comboBoxFilter1 的事件
    if (watched == ui->comboBoxFilter1)
    {
        // 处理鼠标点击事件
        if (event->type() == QEvent::MouseButtonPress)
        {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);

            // 检查是否是左键点击
            if (mouseEvent->button() == Qt::LeftButton)
            {
                // 加载数据
                loadComboxData();
                // 显示下拉菜单
                ui->comboBoxFilter1->showPopup();
                // 返回 true 表示已处理该事件，阻止继续传播
                return true;
            }
        }
    }
    // 其他事件交给基类处理
    return QWidget::eventFilter(watched, event);
}

void AdminDeviceManage::setupUI()
{
    ui->tableView->setModel(model);
    ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableView->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::EditKeyPressed);
    ui->tableView->verticalHeader()->hide();
    ui->tableView->resizeColumnsToContents();
    connect(ui->btnAddDevice, &QPushButton::clicked, this, &AdminDeviceManage::addDevice);
    connect(ui->btnDeleteDevice, &QPushButton::clicked, this, &AdminDeviceManage::deleteDevice);
    connect(ui->btnSaveInfo, &QPushButton::clicked, this, &AdminDeviceManage::saveChanges);
    //connect(ui->btnRefresh, &QPushButton::clicked, this, &AdminUserManage::loadData);
}

void AdminDeviceManage::loadData()
{
    if (!m_pSqliteManage->openDatabase("C:/Users/shafl/Desktop/FrameWork/test.db")) {
        qDebug() << "Failed to open database:" << m_pSqliteManage->lastError();
        //emit sendMessage("数据库连接错误");
        return;
    }
    model->setTable("devices");
    model->select();
    ui->tableView->hideColumn(0); // 隐藏ID列
}

void AdminDeviceManage::addDevice()
{
    QSqlRecord record = model->record();
    record.setValue("name", "新设备");
    record.setValue("type", "设备类型");
    record.setValue("location", "位置");
    record.setValue("manufacturer", "制造商");
    record.setValue("model", "型号");
    QDateTime currentTime = QDateTime::currentDateTime();
    QString dateTimeStr = currentTime.toString("yyyy-MM-dd");
    record.setValue("installation_date", dateTimeStr);

    if (model->insertRecord(-1, record)) {
        ui->tableView->scrollToBottom();
    }
    m_pLog->log(m_pSqliteManage,OPERATION_LOG,WARNING,QString("添加设备数据"),
                m_pSqliteManage->getUserIdByName(username));
}

void AdminDeviceManage::deleteDevice()
{
    QModelIndexList selected = ui->tableView->selectionModel()->selectedRows();
    if (selected.isEmpty()) return;
    if (QMessageBox::question(this, tr("确认"), tr("确定删除选中用户？")) == QMessageBox::Yes) {
        foreach (const QModelIndex &index, selected) {
            model->removeRow(index.row());
        }
    }
    m_pLog->log(m_pSqliteManage,OPERATION_LOG,WARNING,QString("删除设备数据"),
                m_pSqliteManage->getUserIdByName(username));
    saveChanges();
}

void AdminDeviceManage::saveChanges()
{
    if (!model->submitAll()) {
        QMessageBox::critical(this, tr("错误"),
            tr("保存失败：%1").arg(model->lastError().text()));
        model->revertAll();
    } else {
        QMessageBox::information(this, tr("成功"), tr("修改已保存！"));
    }
}
